// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  const bookId = event.bookId
  const booksDb = cloud.database().collection('books')
  const usersDb = cloud.database().collection('users')
  const bookData = await booksDb.where({
    bookId
  }).get()
  const userData = await usersDb.where({
    openid
  }).get()
  const book = bookData.data[0]
  const user = userData.data[0]

  if (!user.permission) {
    return {
      status: -1,
      msg: '封禁状态无法借阅！请联系管理员！'
    }
  }

  // 先判断是否已经拥有
  for (let i = 0; i < user.books.length; i++) {
    if (user.books[i].bookId === bookId) {
      return {
        status: -1,
        msg: '已拥有该书籍！'
      }
    }
  }
  // 再判断是否能借
  // 如果能借，则给该用户添加
  if (book.status) {
    // 用户拥有书籍数目 +1
    user.books.push({
      bookId: book.bookId,
      bookName: book.bookName,
      // 生成借阅时间
      borrowTime: Date.now(),
      // 刚借不会超时
      status: false
    })
    // 添加 book.owners 数组
    book.owners.push(user._id)
    delete user._id
    // user 状态改变
    user.bookCount += 1
    user.status = 1
    await usersDb.where({
      openid
    }).update({
      data: user
    })
    // 书籍剩余数 -1
    book.remain--
    // 剩余数为0，则不可借
    if (book.remain === 0) {
      book.status = false
    }
    delete book._id
    await booksDb.where({
      bookId
    }).update({
      data: book
    })
    return {
      status: 0,
      msg: '借阅成功！'
    }
  } else {
    return {
      status: -2,
      msg: '借阅失败！'
    }
  }

}